package com.duyutian.zhanglong.p8类聊天室;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.UUID;

/**
 * 自定义处理器
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        System.out.println("接受到了消息");
        //发送给聊天室
        channelGroup.forEach(item -> {
            if (item == ctx.channel()) {
                item.writeAndFlush("自己:" + msg + "\r\n");

            } else {
                item.writeAndFlush(ctx.channel().remoteAddress() + " 说: " + msg + "\r\n");
            }
        });
    }


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + "加入了服务器");
        channelGroup.writeAndFlush("加入了聊天室 用户:" + channel.remoteAddress() + "\n");
        channelGroup.add(channel);
    }

    /**
     * 退出聊天室
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

        channelGroup.writeAndFlush("离开了聊天室 用户:" + ctx.channel().remoteAddress() + "\n");
    }


    /**
     * 发生错误 打印日志
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
